<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="X-UA-Compatible" content="IE=EDGE" charset=UTF-8/>
		<link rel="stylesheet" type="text/css" href="resources/styles/GeneralStyle.css"/>
		<title>BCF - Scope Definition</title>
		<script id="sap-ui-bootstrap"
	  		data-sap-ui-theme="sap_ux"
      		type="text/javascript"
       		data-sap-ui-libs="sap.ui.commons"
      		src="resources/sap-ui-core.js">
    	</script > 
		<script src="resources/JavaScript/common.js"></script>
		<script src="resources/JavaScript/utils.js"></script>
		<script>
		var imgRemoveSource = "resources/images/btnRemove.png";
		
		function validateForm()
    	{
			var validateReq = getXmlHttpRequestObject();
			var isValid = false;
			
			function handleRequest()  
   			{  
   			    if (validateReq.readyState == 4 && validateReq.status == 200) 
   			    {
   			     	eval("var response = ("+validateReq.responseText+")");
   			     	
   			     	if(response.message != null) 
		     			showValidationError(response.message);
   			     	
   			     	if(!showSpecifcErrorMessage(response))
   			     	{
   			     		isValid = true;
   			     		refreshPage();
   			     	}
   			    }
   			}
   			
			var param = "&BC=" + encapsulateJSONBcData();
			param += "&cases=" + encapsulateJSONCasesData();
			sendRequest(validateReq, "scope", "saveScopeData", handleRequest, param);
    		
    		return isValid;
    	}

		function encapsulateJSONCasesData()
		{
			var cases = [];
			var caseElements = document.getElementsByName("tbxCaseName");
				for(var i = 0 ; i < caseElements.length ; i++)
				{
					var casID = caseElements[i].id.replace("name","");
					if( caseElements[i].value != null)
					{
						var caso = {"ID": casID, "name": caseElements[i].value, "description": document.getElementById("description" + casID).value};
						cases.push(caso);
					}
				}
				
				return transformJSON(cases);
		}
		
		function encapsulateJSONBcData()
		{
 			var solID = ("${Sol.ID}" == "") ? generateID() : "${Sol.ID}";
 			var bcID = ("${BC.ID}" == "") ? generateID() : "${BC.ID}";
 			
 			var bcSolution = {"ID": solID, "name": document.getElementById("tbxSolName").value, "outOfScope": document.getElementById("tbxSolOut").value, 
 					"description": document.getElementById("taSolDes").value, "assumptions": document.getElementById("tbxSolAssumptions").value};
 			
			var BC = {"ID": bcID, "solID": solID, "name": document.getElementById("tbxBcName").value, "domain" : document.getElementById("tbxDomain").value, 
					"subDomain": document.getElementById("tbxSubDomain").value, "challenge": document.getElementById("taChallenge").value, 
					"author": document.getElementById("tbxAuthor").value, "experts": document.getElementById("tbxExperts").value, "perspective": document.getElementById("tbxPers").value, 
					"decisionMaker": document.getElementById("tbxDesMaker").value, "solution": bcSolution};
			
			return transformJSON(BC);
		}
		
		function verifyPendingChanges()
    	{
			var hasChange = false;
   			var changesReq = getXmlHttpRequestObject();
  				
   			function handleRequest()  
   			{  
   			    if (changesReq.readyState == 4 && changesReq.status == 200)
   			    {
   			    	eval("var response = (" + changesReq.responseText + ")");
   			    	if(response != "ERROR")
   			    		hasChange = response;
   			     	else if(!confirm("Sorry, there was a problem while trying to read the data from the page and pending changes cannot be detected. See log for more details.\nDo you want to continue anyway?"))
 			     		hasChange = "ABORT";
   			    } 
   			}
   			
   			if (changesReq.readyState == 4 || changesReq.readyState == 0)   
		    {  
   				var param = "&BC=" + encapsulateJSONBcData();
   				param += "&cases=" + encapsulateJSONCasesData();
   				sendRequest(changesReq, "scope", "verifyPendingChanges", null, param);
		    }  
    		
    		return hasChange;
    	}
		
		function addCase()
		{
			function updateCaseLegend_JSEvent(){ updateCaseLegend(arguments[0].srcElement); }
			function removeCase_JSEvent(){ before_removeCase(arguments[0].srcElement); }
			
			function createUnderlyingDiv(lbText, secondChildDiv)
			{
				var lb = document.createElement("label");
				lb.innerHTML = lbText;
				var childDiv = document.createElement("div");
				childDiv.setAttribute("class","inputFieldName");
				childDiv.appendChild(lb);
				var div = document.createElement("div");
				div.setAttribute("class","inputNameAndField");
				div.appendChild(childDiv);
				div.appendChild(secondChildDiv);
				
				return div;
			}
			
			try
			{
				var casID = generateID();
				var nameInput = createInputField("name" + casID, "tbxCaseName", "text", "", "scopeField", "onchange", updateCaseLegend_JSEvent);
				var nameDiv = document.createElement("div");
				nameDiv.setAttribute("class", "inputField");
				nameDiv.appendChild(nameInput);
				
				var textArea = document.createElement("textarea");
				textArea.id = "description" + casID;
				textArea.name = "tbxCaseDescription";
				textArea.rows = 3;
				textArea.setAttribute("class","scopeField");
				var descriptionDiv = document.createElement("div");
				descriptionDiv.setAttribute("class", "inputField");
				descriptionDiv.appendChild(textArea);
				
				var caseFieldset = document.createElement("fieldset");
				caseFieldset.id = casID;
				var caseFieldsetLegend = document.createElement("legend");
				caseFieldsetLegend.id = "legend" + casID;
				caseFieldsetLegend.innerHTML = " Properties";
				caseFieldsetLegend.appendChild(createImageButton("remove" + casID, imgRemoveSource, removeCase_JSEvent, "smallImgButton"));
				caseFieldset.appendChild(caseFieldsetLegend);
				caseFieldset.appendChild(createUnderlyingDiv("Case name:", nameDiv));
				caseFieldset.appendChild(createUnderlyingDiv("Case description:", descriptionDiv));
				
				var scopeForm = document.getElementById("scopeForm");
				scopeForm.appendChild(caseFieldset);
			}
			catch(ex)
			{
				showErrorMessage("There was an error while trying to insert a new case and the action couldn't be completed.", "Javascript Error");
				console.log(ex);
			}
		}
		
		function before_removeCase(srcElement)
		{
			function removeCase(oAction)
			{
				if(oAction == sap.ui.commons.MessageBox.Action.YES)
				{
					var casID = srcElement.id.replace("remove","");
					var fsCase = document.getElementById(casID);
					fsCase.parentNode.removeChild(fsCase);
				}
			}
			
			if(document.getElementsByName("tbxCaseName").length > 1)
				sap.ui.commons.MessageBox.show("Are you sure you want to remove this case and all of its related data?", sap.ui.commons.MessageBox.Icon.QUESTION, "Remove Confirmation", [sap.ui.commons.MessageBox.Action.YES, sap.ui.commons.MessageBox.Action.NO], removeCase);
			else
				showErrorMessage("Cannot remove case: At least one case should be entered in the Business Case.", "Invalid Action Error");
		}
		
		function updateCaseLegend(srcElement)
		{
			function removeCase_JSEvent(){ removeCase(arguments[0].srcElement); }
			
			var casID = srcElement.id.replace("name","");
			var caseLegend = document.getElementById("legend" + casID);
			caseLegend.innerHTML= srcElement.value + " Properties";
			caseLegend.appendChild(createImageButton("remove" + casID, imgRemoveSource, removeCase_JSEvent, "smallImgButton"));
		}
		</script>
		<style type="text/css">
			fieldset
			{
				margin-top: 3%;
				border-radius: 10px;
				width: 1000px;
			}
			
			.inputFieldName
			{
				width:100px;
				border:0px solid;
				margin:0px;
				padding:0px;
				float:left;
			}
	
			.inputNameAndField
			{
				display:block;
				border:0px solid;
				padding:0px;
				width:1000px;
				clear:all;
			}
	
			.inputField
			{
				float:left;
				border:0px solid;
				width:800px;
				margin:0px;
				padding:0px;
			}
		</style>
	</head>
	<body onload="initializePage('lnkScope','BCF - Scope Definition')">
		<%@include file="/webPages/_header.jsp"%> 
		<div id="preview" class="sapUiBody">
			<form id="scopeForm" autocomplete="on" action="scope" method="post">
				<fieldset title="Business Case Properties" id="fsBC">
	 				<legend>Business Case Properties</legend>
	 				<div class="inputNameAndField">
						<div class="inputFieldName"><label>BC Name: </label></div> 
						<div class="inputField"><input type="text" class="scopeField" id="tbxBcName" name="name" value="${BC.name}"></div>
					</div>
	 			</fieldset>
				<fieldset id="fsDomain">
					<legend>Domain Properties</legend>
					<div class="inputNameAndField">
						<div class="inputFieldName"><label>Domain: </label></div> 
						<div class="inputField"><input id="tbxDomain" name="domain" class="scopeField" type="text" value="${BC.domain}"></div>
					</div>
					<div class="inputNameAndField">
						<div class="inputFieldName"><label>SubDomain: </label></div> 
						<div class="inputField"><input id="tbxSubDomain" name="subDomain" type="text" class="scopeField" value="${BC.subDomain}"></div>
					</div>
				</fieldset>
				<fieldset id="fsChallenge">
					<legend>Challenge</legend>
					<div class="inputNameAndField">
						<div class="inputFieldName"><label>Description:</label></div> 
						<div class="inputField"><textarea id="taChallenge" name="challenge" class="scopeField" rows="4">${BC.challenge}</textarea></div>
					</div>
				</fieldset>
				<fieldset id="fsSolution">
					<legend>Solution Properties</legend>
					<div class="inputNameAndField">
						<div class="inputFieldName"><label>Solution: </label></div> 
						<div class="inputField"><input id="tbxSolName" name="name" type="text" class="scopeField" value="${Sol.name}"></div>
					</div>
					<div class="inputNameAndField">
						<div class="inputFieldName"><label>Assumptions: </label></div> 
						<div class="inputField"><input id="tbxSolAssumptions" name="assumptions" type="text" class="scopeField" value="${Sol.assumptions}"></div>
					</div>
					<div class="inputNameAndField">
						<div class="inputFieldName"><label>Out of Scope: </label></div> 
						<div class="inputField"><input id="tbxSolOut" name="outOfScope" type="text" class="scopeField" value="${Sol.outOfScope}"></div>
					</div>
					<div class="inputNameAndField">
						<div class="inputFieldName"><label>Solution Description: </label></div> 
						<div class="inputField"><textarea id="taSolDes" name="description" class="scopeField" rows="4">${Sol.description}</textarea></div>
					</div>
				</fieldset>
				<c:choose>
					<c:when test="${Cases != null}">
						<c:forEach var="caso" items="${Cases}">
							<fieldset id="${caso.ID}">
								<legend id="legend${caso.ID}">${caso.name} Properties
									<img src="resources/images/btnRemove.png" id="remove${caso.ID}" onclick="before_removeCase(this)" class="smallImgButton">
								</legend>
								<div class="inputNameAndField">
									<div class="inputFieldName"><label>Case name: </label></div>
									<div class="inputField"><input id="name${caso.ID}" name="tbxCaseName" class="scopeField" type="text" value="${caso.name}" onchange="updateCaseLegend(this)"></div> 
								</div>
								<div class="inputNameAndField">
									<div class="inputFieldName"><label>Case description:</label> </div> 
									<div class="inputField"><textarea id="description${caso.ID}" name="tbxCaseDescription" class="scopeField" rows="3">${caso.description}</textarea></div>
								</div>
							</fieldset>
						</c:forEach>
					</c:when>
					<c:otherwise>
						<c:set var="case1_ID" value="case1"/>
						<fieldset id="${case1_ID}">
							<legend id="legend${case1_ID}">Case Properties
								<img src="resources/images/btnRemove.png" id="remove${case1_ID}" onclick="before_removeCase(this)" class="smallImgButton">
							</legend>
							<div class="inputNameAndField">
								<div class="inputFieldName"><label>Case name: </label></div>
								<div class="inputField"><input id="name${case1_ID}" name="tbxCaseName" class="scopeField" type="text" onchange="updateCaseLegend(this)"></div> 
							</div>
							<div class="inputNameAndField">
								<div class="inputFieldName"><label>Case description:</label> </div> 
								<div class="inputField"><textarea id="description${case1_ID}" name="tbxCaseDescription" class="scopeField" rows="3"></textarea></div>
							</div>
						</fieldset>
					</c:otherwise>
				</c:choose>
				<input type="button" id="btnAddCase" class="buttonStyle" value="Add more cases..." onclick="addCase()">
				<fieldset id="fsStakeholders">
					<legend>Stakeholders</legend>
					<div class="inputNameAndField">
						<div class="inputFieldName"><label>Author: </label></div> 
						<div class="inputField"><input id="tbxAuthor" name="author" class="scopeField" type="text" value="${BC.author}"></div>
					</div>
					<div class="inputNameAndField">
						<div class="inputFieldName"><label>Experts: </label></div> 
						<div class="inputField"><input id="tbxExperts" name="experts" class="scopeField" type="text" value="${BC.experts}"></div>
					</div>
					<div class="inputNameAndField">
						<div class="inputFieldName"><label>Perspective: </label></div> 
						<div class="inputField"><input id="tbxPers" name="perspective" class="scopeField" type="text" value="${BC.perspective}"></div>
					</div>
					<div class="inputNameAndField">
						<div class="inputFieldName"><label>Decision Maker: </label></div> 
						<div class="inputField"><input id="tbxDesMaker" name="decisionMaker" class="scopeField" type="text" value="${BC.decisionMaker}"></div>
					</div>
				</fieldset>
				<input type="button" value="Submit Changes" class="formButton" onclick="validateForm()">
			</form>
		</div>
		<%@include file="/webPages/_footer.jsp"%>
	</body>
</html>